package com.naiterui.ehp.bs.im.repository.file;

import com.naiterui.ehp.bp.support.security.HeaderConstant;
import com.naiterui.ehp.bs.im.config.MediaFileConfig;
import com.naiterui.ehp.bs.im.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 聊天多媒体文件的存储
 */
@Service
public class MediaFileHandler {

    /**
     * 路径分隔符
     */
    private static final String SEPARATOR = "/";

    /**
     * 文件名称与后缀名的间隔符
     */
    private static final String DOT = ".";

    /**
     * 文件名：<code>SUFFIX_MP3</code>
     */
    private static final String SUFFIX_MP3 = "mp3";
    /**
     * 字段或域定义：<code>SUFFIX_AMR</code>
     */
    private static final String SUFFIX_AMR = "amr";

    /**
     * 媒体文件存储配置信息
     */
    @Autowired
    private MediaFileConfig config;

    /**
     * 保存图片文件
     */
    public String saveImage(Long fromId, Long toId, byte[] data) {
        String fileName = this.generateFileName() + DOT + config.getImageFormat();
        String root = config.getImageRoot();
        String storgePath = fromId + SEPARATOR + toId + SEPARATOR + DateUtils.formatDate() + SEPARATOR + fileName;
        IOHandler.saveFile(root + storgePath, data);
        return config.getServerDomain() + config.getImageRewrite() + storgePath;
    }

    /**
     * 保存音频文件
     */
    public String saveRadio(int origin, int platform, Long fromId, Long toId, byte[] data) {
        String fileName = this.generateFileName() + DOT;
        // 转码调整（APP端统一mp3格式上传，微信端amr格式上传）
        if (origin == HeaderConstant.HEADER_ORIGIN_PATIENT_WX) {
            // 微信端上传格式：amr格式
            fileName += SUFFIX_AMR;
        } else if (platform == HeaderConstant.HEADER_PLATFORM_ANDROID_PHONE) {
            // 安卓端上传格式：mp3格式
            fileName += SUFFIX_MP3;
        } else if (platform == HeaderConstant.HEADER_PLATFORM_IOS_PHONE) {
            // IOS上传格式：mp3格式
            fileName += SUFFIX_MP3;
        }

        String root = config.getRadioRoot();
        String storgePath = fromId + SEPARATOR + toId + SEPARATOR + DateUtils.formatDate() + SEPARATOR + fileName;
        IOHandler.saveFile(root + storgePath, data);
        return config.getServerDomain() + config.getRadioRewrite() + storgePath;
    }

    /**
     * 保存视频文件
     */
    public String saveVideo(Long fromId, Long toId, byte[] data){
        String fileName = this.generateFileName() + DOT + config.getVideoFormat();
        String root = config.getVideoRoot();
        String storgePath = fromId + SEPARATOR + toId + SEPARATOR + DateUtils.formatDate() + SEPARATOR + fileName;
        IOHandler.saveFile(root + storgePath, data);
        return config.getServerDomain() + config.getVideoRewrite() + storgePath;
    }

    /**
     * 生成文件名称
     */
    private String generateFileName() {
        return System.currentTimeMillis() + "";
    }
}
